// pages/login/company/company.js
import uploadImg from '../../../utils/uploadImg.js'
import {
  $wuxSelect
} from '../../../wux-components/index'
import {
  edu,
  street,
  salary,
  jobIntention,
  staffNumber
} from '../../../utils/base-data.js'
const T = getApp().globalData.T
const config = getApp().globalData.config
let token = '';
let role = '';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    uploadUrl: config.host + 'admin/file/singleFile',
    isOpenMap: false,
    formData: {
      type: 'image'
    },
    company: '',
    creditNo: '',
    isEdit: '',
    step3Show: false,
    moneyArray: salary,
    input01: '',
    input02: '',
    input03: '',
    input04: '',
    input05: '',
    input06: '',
    item01: {
      title: '请选择'
    },
    item02: {
      title: '请选择'
    },
    item03: {
      title: '请选择'
    },
    liceseImg: '/resource/image/create_comp_license.png',
    logo: '/resource/image/create_comp_logo.png',
    btnText: '提交审核',
    location: '', //	公司经纬度信息
    fileList: [],
    isShare: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.setData({ isShare: options.userId });
    // 通过分享进入，且无 token
    if (options.userId && !getApp().globalData.token) {
      const params = {
        userId: options.userId,
        userType: 1
      }
      wx.redirectTo({
        url: '/pages/login/index?' + T.param(params)
      });
    }
    
    token = getApp().globalData.token;
    role = getApp().globalData.role;
    if (options.origin == 'edit') { // 通过编辑进入
      wx.setNavigationBarTitle({
        title: '公司资料'
      });
      this.setData({
        btnText: '保存修改',
        isEdit: true,
        role: role
      })
      this.getDetail();
    } else {
      this.setData({
        company: options.company,
        creditNo: options.creditNo,
        isShowUpload: true
      })
    }
    this.showMap();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    
  },

  getDetail() {
    T.req({
      loadTitle: '加载中...',
      url: config.api + 'user/company_info',
      method: 'GET',
      data: {
        token: token
      },
      success: (res) => {
        this.setData({
          company: res.fullName,
          input01: res.shortName,
          creditNo: res.taxpayerId,
          liceseImg: res.businessLicense,
          logo: res.logo,
          item01: { title: res.industryName, value: res.industryId},
          ['item02.title']: res.staffNumber,
          input02: res.detailAddress || '广州科学城开泰大道天泰一路3号',
          ['item03.title']: res.street,
          input03: res.intro,
          input04: res.website,
          input05: res.officePhone,
          input06: res.extensionNum
        });
        let tem = [];
        res.photos.forEach((m, i) => {
          console.log(m);
          tem.push({
            url: m
          })
        });

        this.setData({
          fileList: tem,
          isShowUpload: true,
        });
        this.getLocation(this.data.input02);
        console.log(this.data.input01)
      }
    })

  },

  onInput01(e) {
    this.setData({
      input01: e.detail.value
    })
  },
  onInput02(e) {
    this.setData({
      input02: e.detail.value
    });
    this.getLocation(e.detail.value.trim());
  },
  onInput03(e) {
    this.setData({
      input03: e.detail.value
    })
  },
  onInput04(e) {
    this.setData({
      input04: e.detail.value
    })
  },
  onInput05(e) {
    this.setData({
      input05: e.detail.value
    })
  },
  onInput06(e) {
    this.setData({
      input06: e.detail.value
    })
  },

  showMap(lt, la) {
    this.setData({
      longitude: lt || 116.397726,
      latitude: la || 39.903767,
      markers: [{
        iconPath: "/resource/image/marker.png",
        id: 0,
        longitude: lt || 116.397726,
        latitude: la || 39.903767,
        width: 20,
        height: 30
      }]
    })
  },


  getLocation(value) {
    T.req({
      url: config.api + 'geocode',
      method: 'GET',
      data: {
        token: token,
        address: value
      },
      success: (res) => {
        if (JSON.stringify(res) == '{}') return;
        this.setData({
          location: res.location
        });
        if (!value) return;
        let lt = res.location.split(',')[0];
        let la = res.location.split(',')[1];
        console.log(lt, la)
        this.showMap(lt, la);
      }
    })

  },

  onJobIntro(e) {
    this.setData({
      input03: e.detail.value
    })
  },

  onUploadSuccess(e) {
    this.data.fileList.push({
      url: JSON.parse(e.detail.fileList.slice(-1)[0].res.data).data.url
    })
  },

  onUploadFail(e) {
    console.log(e);
  },

  onRemoveImg(e) {
    this.data.fileList.splice(e.detail.index, 1);
  },

  onClickIndustry() {
    this.setData({ isOpenMap: true, step3Show:true});
    $wuxSelect('#wux-select-industry').open({
      value: '',
      options: getApp().globalData.industryList,
      onConfirm: (value, index, options) => {
        if (index !== -1) {
          this.setData({
            value2: value,
            item01: options[index],
            isOpenMap: false,
            step3Show:false,
          })
        }
      },
      onCancel: () => {
        this.setData({ isOpenMap: false, step3Show: false});
      }
    });
  },

  onClickStaff() {
    this.setData({ isOpenMap: true, step3Show: true});
    $wuxSelect('#wux-select-staff').open({
      value: '',
      options: staffNumber,
      onConfirm: (value, index, options) => {
        if (index !== -1) {
          this.setData({
            value2: value,
            item02: options[index],
            isOpenMap: false,
            step3Show: false,
          })
        }
      },
      onCancel: () => {
        this.setData({ isOpenMap: false, step3Show: false });
      }
    });
  },

  onClickStreet() {
    this.setData({ isOpenMap: true, step3Show: true });
    $wuxSelect('#wux-select-row').open({
      value: '',
      options: street,
      onConfirm: (value, index, options) => {
        if (index !== -1) {
          this.setData({
            value2: value,
            item03: options[index],
            isOpenMap: false,
            step3Show: false
          })
        }
      },
      onCancel:() => {
        this.setData({ isOpenMap: false, step3Show: false });
      }
    });
  },

  onSelectLiceseImg() {
    let that = this;
    if (this.data.isEdit) return ;
    uploadImg(that, 'image', 'uploadLice')
      .then((res) => {
        that.setData({
          liceseImg: res,
          isOpenMap: false
        })
      })
  },

  onSelectLogoImg() {
    let that = this;
    uploadImg(that, 'image', 'uploadLogo')
      .then((res) => {
        that.setData({
          logo: res,
          isOpenMap: false
        })
      })
  },

  getValue() {
    let obj = {};
    obj.fullName = this.data.company;
    obj.shortName = this.data.input01;
    obj.taxpayerId = this.data.creditNo;
    obj.businessLicense = this.data.liceseImg;
    obj.logo = this.data.logo;
    obj.industryName = this.data.item01.title;
    obj.staffNumber = this.data.item02.title;
    obj.detailAddress = this.data.input02;
    obj.street = this.data.item03.title;

    let isError = false;
    for (const k in obj) {
      if (!obj[k] || obj[k] == '请选择') {
        isError = true;
      }
    }

    if (isError) {
      wx.showToast({
        title: '还有选项没有选择或者输入,请检查',
        icon:'none'
      });
      isError = true;
      
    } 
    obj.intro = this.data.input03;
    obj.website = this.data.input04;
    obj.officePhone = this.data.input05;
    obj.extensionNum = this.data.input06;
    obj.photos = this.data.fileList;
    obj.industryId = this.data.item01.value;
    
    let _tem = [];
    obj.photos.forEach((m) => {
      _tem.push(m.url);
    })
    obj.photos = _tem;

    obj.location = this.data.location;
    return {isError: isError, obj: obj};

  },

  onEditCompanyInfo() {
    let obj = this.getValue().obj;
    let isError = this.getValue().isError;
    console.log(obj);
    if (isError) {
      console.log('输入有错');
      return;
    }
    T.req({
      loadTitle: '请求中...',
      url: config.api + 'user/companyinfo?token=' + token,
      method: 'PUT',
      data: {
        logo: obj.logo,
        industryId: obj.industryId,
        industryName: obj.industryName,
        staffNumber: obj.staffNumber,
        detailAddress: obj.detailAddress,
        street: obj.street,
        location: obj.location,
        intro: obj.intro,
        website: obj.website,
        officePhone: obj.officePhone,
        extensionNum: obj.extensionNum,
        photos: obj.photos
      },
      success: (res) => {
          wx.showToast({
            title: '编辑成功',
            success: () => {
              wx.navigateBack({
                delta: 1
              })
            }
          })
      }
    })

  },

  onCreateCompanyInfo() {
    let obj = this.getValue().obj;
    let isError = this.getValue().isError;
    if (isError) {
      console.log('输入有错');
      return ;
    }
    let userId = getApp().globalData.userId;
    T.req({
      loadTitle: '请求中...',
      url: config.api + 'user/company_info?token=' + token,
      method: 'POST',
      data: {
        userId: userId,
        fullName: obj.fullName,
        shortName: obj.shortName,
        taxpayerId: obj.taxpayerId,
        businessLicense: obj.businessLicense,
        logo: obj.logo,
        industryName: obj.industryName,
        industryId: obj.industryId,
        staffNumber: obj.staffNumber,
        detailAddress: obj.detailAddress,
        street: obj.street,
        location: obj.location,
        intro: obj.intro,
        website: obj.website,
        officePhone: obj.officePhone,
        extensionNum: obj.extensionNum,
        photos: obj.photos
      },
      success: (res) => {
        T.toast({
          id: '#toast',
          text: '创建成功',
          success: () => {
            wx.reLaunch({
              url: '../status/status',
            })
          }
        });
      }
    })
  },

  onSubmit() {
    if (this.data.isEdit) { // 编辑资料
      this.onEditCompanyInfo();
    } else { // 创建公司
      this.onCreateCompanyInfo();
    }
  }
})